//Copyright 2012 Trevin Liberty
//GNU GPL v3
//Author: Trevin Liberty

#include "Map_Loader.h"

#include "Doohickeys\Swordsmen.h"
#include "Doohickeys\Archer.h"

std::list<Entity*>* loadMapP(TiXmlNode* parent, Map* map, std::list<Entity*>* entities) {
		if(!parent)
			return entities;

		int t = parent->Type();
		int x, y, attr;

		TiXmlElement* element;
		TiXmlNode* child;

		switch(t) {

		case TiXmlNode::TINYXML_ELEMENT:
			if(strcmp(parent->Value(), "Tile") == 0) {
				element = parent->ToElement();
				element->Attribute("x", &x);
				element->Attribute("y", &y);
				element->Attribute("Walkable");

				if(strcmp(element->Attribute("Walkable"), "1") == 0)
					map->mapArray[x][y]->walkable = true;
				else
					map->mapArray[x][y]->walkable = false;

				element->Attribute("Base", &attr);
				map->mapArray[x][y]->base = attr;
				element->Attribute("Fringe", &attr);
				map->mapArray[x][y]->fringe = attr;
				element->Attribute("Object", &attr);
				map->mapArray[x][y]->objectType = attr;
				element->Attribute("Cost", &attr);
				map->mapArray[x][y]->cost = attr;
				map->mapArray[x][y]->object = NULL;
				map->mapArray[x][y]->doohickey = NULL;

				element->Attribute("Entity", &attr);
				if(attr > 0) {
					int t = 1;
					if(strcmp(element->Attribute("team"), "1") == 0)
						t = 0;

					Entity* e;
					if(attr == 1) {
						e = new Swordsmen(100, map, NULL);
						e->initEntity(10, 0, 1, 1.5, 1.5);
					}
					else {
						e = new Archer(100, map, NULL);
						e->initEntity(10, 0, 1, 1.5, 10.0);
					}
					e->setTeam(t);
					e->setXY(x*32 + 16, y*32 + 16);
					entities->push_back(e);
				}
			}
			else if(strcmp(parent->Value(), "Params") == 0) {
				element = parent->ToElement();
				element->Attribute("TileSize", &map->tileSize);
				element->Attribute("NumTilesX", &map->numTilesX);
				element->Attribute("NumTilesY", &map->numTilesY);
				
				map->mapArray = new mapCell**[map->numTilesX];
				for(int i = 0; i < map->numTilesX; i++) {
					map->mapArray[i] = new mapCell*[map->numTilesY];
					for(int j = 0; j < map->numTilesY; j++) {
						map->mapArray[i][j] = new mapCell();
						map->mapArray[i][j]->x = i*map->tileSize + map->tileSize/2;
						map->mapArray[i][j]->y = j*map->tileSize + map->tileSize/2;
					}
				}

			}
		}

		for(child = parent->FirstChild(); child != 0; child = child->NextSibling())
			loadMapP(child, map, entities);
		return entities;
}

std::list<Entity*>* loadMap(Map* map) {
	TiXmlDocument doc("level/LV1.xml");
	if(doc.LoadFile()) {
		map->mapArray = NULL;
		std::list<Entity*>* entities = new std::list<Entity*>;
		return loadMapP(&doc, map, entities);
	}
	else {
		std::cout << "ERROR LOADING LEVEL";
		return NULL;
	}

}